package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private static final String LOCK_PREFIX = "lock:";
    private static final String THREADID_PREFIX = UUID.randomUUID().toString(true)+"-";//线程标识
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String threadId = THREADID_PREFIX+Thread.currentThread().getId();
        Boolean aboolean =  stringRedisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(aboolean);//true返回true  false和null返回false 防止自动拆箱空指针问题
    }

    @Override
    public void unlock() {//改进2 使用lua脚本
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(LOCK_PREFIX+name),
                THREADID_PREFIX+Thread.currentThread().getId());
    }

//    @Override
//    public void unlock() {//改进1
//        String threadId = THREADID_PREFIX+Thread.currentThread().getId();
//        String id = stringRedisTemplate.opsForValue().get(LOCK_PREFIX+name);
//        if(threadId.equals(id)){//释放的是否是自身获取的锁
//            stringRedisTemplate.delete(LOCK_PREFIX+name);
//        }
//    }



}
